'use strict';
/*-----------时间--------*/
import moment from 'moment';
const basic = require('./basic')
moment.locale('zh-cn');
/*------------Redis部分定义----------*/
const Redis = require('ioredis');
import YAML from 'yamljs';
const Settings = YAML.load('settings.yaml');
const REDIS_GATEWAY = Settings.REDIS_GATEWAY;
const redisHost = REDIS_GATEWAY.redisHost;
const redisPort = REDIS_GATEWAY.redisPort;
const events = require("events");
const EventEmitter = events.EventEmitter || events;
class RedisGatewayClass extends EventEmitter {
  pubRedisCli: any
  subRedisCli: any
  localPubRedisCli: any
  localSubRedisCli: any
  constructor() {
    super();

    // the serial port to use
    this.pubRedisCli = new Redis(redisPort, redisHost);
    this.subRedisCli = new Redis(redisPort, redisHost);
    this.localPubRedisCli = new Redis(6379, "127.0.0.1");
    this.localSubRedisCli = new Redis(6379, "127.0.0.1");
    // 监听连接事件
    this.pubRedisCli.on('connect', () => {
      console.log('pubRedisCli connected');
    });
    // 监听错误事件
    this.pubRedisCli.on('error', (err) => {
      console.error('pubRedisCli error', err);
    });
    // 监听断开连接事件
    this.pubRedisCli.on('close', () => {
      console.log('pubRedisCli closed');
    });
    // 监听重新连接事件
    this.pubRedisCli.on('reconnecting', () => {
      console.log('pubRedisCli reconnecting');
    });
    // 监听重新连接成功事件
    this.pubRedisCli.on('ready', () => {
      console.log('pubRedisCli ready');
    });
    // 监听重新连接失败事件
    this.pubRedisCli.on('end', () => {
      console.log('pubRedisCli end');
    });
    // 设置断线重连机制
    this.pubRedisCli.on('end', () => {
      setTimeout(() => {
        console.log('pubRedisCli try to reconnect');
        this.pubRedisCli.connect();
      }, 3000);
    });

    // 监听连接事件
    this.localPubRedisCli.on('connect', () => {
      console.log('localPubRedisCli connected');
    });
    // 监听错误事件
    this.localPubRedisCli.on('error', (err) => {
      console.error('localPubRedisCli error', err);
    });
    // 监听断开连接事件
    this.localPubRedisCli.on('close', () => {
      console.log('localPubRedisCli closed');
    });
    // 监听重新连接事件
    this.localPubRedisCli.on('reconnecting', () => {
      console.log('localPubRedisCli reconnecting');
    });
    // 监听重新连接成功事件
    this.localPubRedisCli.on('ready', () => {
      console.log('localPubRedisCli ready');
    });
    // 监听重新连接失败事件
    this.localPubRedisCli.on('end', () => {
      console.log('localPubRedisCli end');
    });
    // 设置断线重连机制
    this.localPubRedisCli.on('end', () => {
      setTimeout(() => {
        console.log('localPubRedisCli try to reconnect');
        this.localPubRedisCli.connect();
      }, 3000);
    });
    // 监听连接事件
    this.localSubRedisCli.on('connect', () => {
      console.log('localSubRedisCli connected');
    });
    // 监听错误事件
    this.localSubRedisCli.on('error', (err) => {
      console.error('localSubRedisCli error', err);
    });
    // 监听断开连接事件
    this.localSubRedisCli.on('close', () => {
      console.log('localSubRedisCli closed');
    });
    // 监听重新连接事件
    this.localSubRedisCli.on('reconnecting', () => {
      console.log('localSubRedisCli reconnecting');
    });
    // 监听重新连接成功事件
    this.localSubRedisCli.on('ready', () => {
      console.log('localSubRedisCli ready');
    });
    // 监听重新连接失败事件
    this.localSubRedisCli.on('end', () => {
      console.log('localSubRedisCli end');
    });
    // 设置断线重连机制
    this.localSubRedisCli.on('end', () => {
      setTimeout(() => {
        console.log('localSubRedisCli try to reconnect');
        this.localSubRedisCli.connect();
      }, 3000);
    });

    // 监听连接事件
    this.subRedisCli.on('connect', () => {
      console.log('subRedisCli connected');
    });
    // 监听错误事件
    this.subRedisCli.on('error', (err) => {
      console.error('subRedisCli error', err);
    });
    // 监听断开连接事件
    this.subRedisCli.on('close', () => {
      console.log('subRedisCli closed');
    });
    // 监听重新连接事件
    this.subRedisCli.on('reconnecting', () => {
      console.log('subRedisCli reconnecting');
    });
    // 监听重新连接成功事件
    this.subRedisCli.on('ready', () => {
      console.log('subRedisCli ready');
    });
    // 监听重新连接失败事件
    this.subRedisCli.on('end', () => {
      console.log('subRedisCli end');
    });
    // 设置断线重连机制
    this.subRedisCli.on('end', () => {
      setTimeout(() => {
        console.log('subRedisCli try to reconnect');
        this.subRedisCli.connect();
      }, 3000);
    });
    this.RedisConfig();
  }

  /*------------------------------------------*/
  /*-------------Redis 发布部分----------------*/
  /*-----------------------------------------*/
  /**
   * 发送Redis直接控制命令
   * @param {string} cmd 帧指令数据
   */
  PubSerialDirectCmd(cmd: string, retries: number | undefined) {
    let directCmd = {
      "method": "Direct",
      "retries": retries === undefined ? 2 : retries,
      "cmd": cmd
    }
    //console.log(`${new Date().toLocaleString()}`,`[redisPub--->>>SERIAL_CMD] ` + JSON.stringify(directCmd));
    this.pubRedisCli.publish(`SERIAL_CMD`, JSON.stringify(directCmd)); //
  }

  PubEbyteCmd(cmd: string, retries: number | undefined) {
    let directCmd = {
      "method": "Direct",
      "retries": retries === undefined ? 2 : retries,
      "cmd": cmd
    }
    //console.log(`${new Date().toLocaleString()}`,`[redisPub--->>>SERIAL_CMD] ` + JSON.stringify(directCmd));
    this.pubRedisCli.publish(`EBYTE_CMD`, JSON.stringify(directCmd)); //
  }

  /**
   * 发送配肥机指令
   * @param {string} cmd 帧指令数据
   */
  pubFertilizerCmd(ackInfo: any) {
    console.log(`${new Date().toLocaleString()}`, ackInfo)
    this.pubRedisCli.publish(`FERTILIZER_CMD`, JSON.stringify(ackInfo)); //
  }

  /**
   * 
   * @param {string} cmd 帧指令数据
   */
  pubActuatorCmdAck(confType: string, method: string, qryId: string, status: string, msg: string, params: any) {
    let pubData = {
      "confTyp": confType,
      "method": method,
      "qryId": qryId,
      "status": status,
      "msg": msg,
      "para": params
    }
    // console.log('[redisPub-SYS_CMD_ACK]' + JSON.stringify(pubData))
    this.localPubRedisCli.publish('ACTUATOR_ACK', JSON.stringify(pubData)); //
  }
  /**
 * 
 * @param {string} cmd 帧指令数据
 */
  pubSystemCmdAck(confType: string, method: string, qryId: string, status: string, msg: string, params: any) {
    let pubData = {
      "confTyp": confType,
      "method": method,
      "qryId": qryId,
      "status": status,
      "msg": msg,
      "para": params
    }
    //console.log('[redisPub-SYS_CMD_ACK]' + JSON.stringify(pubData))
    this.localPubRedisCli.publish('SYS_CMD_ACK', JSON.stringify(pubData)); //
  }
  /*------------------------------------------*/
  /*-------------Redis 订阅部分----------------*/
  /*-----------------------------------------*/
  /**
   * 订阅Redis执行器信息
   */
  __redisSub_Actuator() {
    this.localSubRedisCli.subscribe('ACTUATOR', function (err: Error | null, count: number) {
      if (err === null) {
        console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----ACTUATOR,Count:${count}`);
      } else {
        console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----${err.toString()}`);
      }
    });
  }


  __redisSub_sysCmd() {
    this.localSubRedisCli.subscribe('SYS_CMD', function (err: Error | null, count: number) {
      if (err === null) {
        console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----SYS_CMD,Count:${count}`);
      } else {
        console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----${err.toString()}`);
      }
    });
  }
  __redisSub_SerialCmdAck() {
    this.subRedisCli.subscribe('SERIAL_CMD_ACK', function (err: Error | null, count: number) {
      if (err === null) {
        // console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----SERIAL_CMD_ACK,Count:${count}`);
      } else {
        console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----${err.toString()}`);
      }
    });
  }

  __redisSub_EbyteCmdAck() {
    this.subRedisCli.subscribe('EBYTE_CMD_ACK', function (err: Error | null, count: number) {
      if (err === null) {
        console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----EBYTE_CMD_ACK,Count:${count}`);
      } else {
        console.log(`${new Date().toLocaleString()}`, `[redisSub]:<-----${err.toString()}`);
      }
    });
  }
  TestSysCmd() {
    let pubInfo = {
      "confTyp": "ROLLER",
      "method": "OPEN_GROUP",
      "para": {
        "zoneId": 1,
        "groupId": [1],
        "open": [50]
      }
    }
    setInterval(() => {
      this.pubRedisCli.publish(`SYS_CMD`, JSON.stringify(pubInfo)); //
    }, 3000)
  }
  /**
 * Redis服务初始化——redisParser(channel,message)：传入解析函数
 * @param {Function} redisParser 
 */
  RedisConfig() {
    const modbus = this;
    /*------------Redis订阅主题Topic-----------------*/
    this.__redisSub_SerialCmdAck();
    this.__redisSub_EbyteCmdAck();
    this.__redisSub_Actuator();
    this.__redisSub_sysCmd();
    /*----------------Redis订阅数据处理-----------------*/
    this.subRedisCli.on('message', modbus.emit.bind(modbus, "message"));
    this.localSubRedisCli.on('message', modbus.emit.bind(modbus, "message"));

  }

}



export {
  RedisGatewayClass
};
